package com.probiz.estoresf.sales.web.action;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.catalog.service.ContentCategoryManager;
import com.probiz.estore.common.model.catalog.ContentCategory;
import com.probiz.estore.common.model.sales.Applicants;
import com.probiz.estore.core.controller.GenericStoreFrontController;
import com.probiz.estore.core.exception.ApplicationException;
import com.probiz.estore.sales.service.ApplicantsManager;

public class ApplicantFrontController extends GenericStoreFrontController<Applicants> {
	private ApplicantsManager applicantsManager;
	private ContentCategoryManager contentCategoryManager;
	public void setContentCategoryManager(ContentCategoryManager contentCategoryManager) {
		this.contentCategoryManager = contentCategoryManager;
	}
	public void setApplicantsManager(ApplicantsManager applicantsManager) {
		this.applicantsManager = applicantsManager;
	}
	protected void initController() throws Exception {
		mgr = applicantsManager; 
		
	}
	public ModelAndView defaultAction(HttpServletRequest request,HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("sales/defaultApplicantsForm");
		String catelogCode = request.getParameter("catelogCode");
		
		if(StringUtils.isEmpty(catelogCode)){//默认进入代理申请页面
			catelogCode = "agentApply";
		}
		
		if(StringUtils.isBlank(catelogCode)){
			try {
				response.sendError(404);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}	
		ContentCategory contentCategory = contentCategoryManager.getCategoryByCode(catelogCode);
		if(null == contentCategory){
			try {
				response.sendError(404);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		
		mv.addObject("categoryCode", contentCategoryManager.getSecondLevelContentCatelogCode(contentCategory));
		request.setAttribute("category", contentCategory);
		return mv;
	}
	
	public ModelAndView save(HttpServletRequest request,HttpServletResponse response){
		String msg = "";
		
		Applicants entity = new Applicants();
		ServletRequestDataBinder binder = bindAndValidate(request, entity, "applicant");
		BindException errors = new BindException(binder.getBindingResult());
		try {
			if (!errors.hasErrors()) {
				mgr.save(entity);
				msg = this.getMessage("applicants.save.success");
			}
		} catch (ApplicationException e) {
			handleApplicationException(errors, e);
			msg = this.getMessage("applicants.save.error");
		}
		this.saveMessage(request, msg);
		return defaultAction(request, response);
	}
}
